/*###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############*/

var JFX_Tree = {

    tree : Array(),
    imageFolder : '/jfx/js/jfx/tree/images',

    init : function(treeId, openBranches){
        alert('loadTree');
        this.loadTree(treeId);
        this.openAllBranches(openBranches);
    },

    repaintNavigation : function(branch){
        alert(branch.id);
        for(var i=0; i<branch.branches.length; i++){
            alert('twig number '+i);
            var twig = branch.branches[i];
            if(i == (branch.branches.length-1)){
                // this is the bottom twig
                $(twig.element).css('background-image', this.imageFolder+'/twig-bottom.gif');

            }else{
                $(twig.element).css('background-image', this.imageFolder+'/twig.gif');
            }
            if(twig.open){
                
            }
        }
    },

    findBranch : function(branchId, branch){
        if(typeof(branch.branches)!=='Array') return false;
        for(var i=0; i<branch.branches.length; i++){
            if(branch.branches[i].id == branchId) return branch.branches[i];
        }
        return false;
    },

    openBranch : function(branchId){
        var branch = this.findBranch(branchId, this.tree);
        branch.open = true;
        this.repaintNavigation(this.tree);
    },

    openAllBranches : function(branchIds){
        for(var i=0; i < branchIds.length; i++){
            this.openBranch(branchIds[i]);
        }
    },

    /**
     * Recursive function to list tree nodes as array elements from a given html list
     */
    findBranches : function(el){
        var listItem = Array();
        var branches = $('ul', el).get();
        var list = Array();
        if(branches.length > 0){
            for(var i=0; i<branches.length; i++){
                var twigs = this.findBranches(branches[i]);
                branches[i] = twigs;
            }
        }
        if(typeof(branches)!=='Array') branches = Array();
        listItem.branches = list;
        listItem.element = el;
        listItem.open = false;
        listItem.id = el.id;
        return listItem;
    },

    loadTree : function(id){
        var tree = $('#'+id).get(0);
        var list = $('li', tree).get();
        for(var i=0; i<list.count; i++){
            list[i] = this.findBranches(tree);
        }
        this.tree.branches = list;
        this.tree.id = id;
        this.tree.element = tree;
        this.tree.open = true;
    }
}